<?php defined('SYSPATH') or die('No direct script access.');

class Model_Sitemap
{ 
    protected static $_links_per_file = 10000; 
 
    public static function generate_sitemap()
    {
        // чистим папку с частями сайтмапов
        self::_clear_sitemap_folder();
            
        // сначала генерим все категории с фильтрами
        $n    = 0;
        $urls = array();
        
        $categories = ORM::factory('category')->find_all();
        foreach ($categories as $category) {
            $_brands = ORM::factory('brand')->get_brands($category);
            $brands  = array();
            if (is_array($_brands)) {
                $brands = array_merge($_brands['main'], $_brands['other']);   
            }
            /*$colors  = Model_Color::get_colors($category);
            $compositions = Model_Composition::get_compositions($category);
            $seasons = Model_Season::get_seasons($category);    */
            
            self::_try_write_file($n, $urls);
            $n++;
            $urls[] = Helper_Index::category_url($category);
            
            foreach ($brands as $brand) {
                self::_try_write_file($n, $urls);
                $n++;
                $urls[] = Helper_Index::category_url($category, $brand);
                
                /*foreach ($colors as $color) {
                    self::_try_write_file($n, $urls);
                    $n++;
                    $urls[] = Helper_Index::category_url($category, $brand, $color);
                    
                    foreach ($compositions as $composition) {
                        self::_try_write_file($n, $urls);
                        $n++;
                        $urls[] = Helper_Index::category_url($category, $brand, $color, $composition);
                        
                        foreach ($seasons as $season) {
                            self::_try_write_file($n, $urls);
                            $n++;
                            $urls[] = Helper_Index::category_url($category, $brand, $color, $composition, $season);    
                        }                     
                    }              
                }  */  
            }
                
        }
        
        if (count($urls)) {
            self::_write_file($urls, $n);    
        }
        
        
        // потом доступные товары
        $part = 1;
        do {
            $limit  = self::$_links_per_file;
            $offset = ($part - 1) * $limit;
            $part++;
            
            $products = ORM::factory('product')
                            ->where('available', '=', 1)
                            ->order_by('id', 'ASC')
                            ->offset($offset)
                            ->limit($limit)
                            ->find_all();
                            
            $urls = array();
            foreach ($products as $product) {
                $urls[] = Helper_Index::product_url($product);    
            }
            if (count($urls)) {
                self::_write_file($urls, $offset + $limit, 'product');    
            } 
        } while (count($products));
        
        // генерим основной сайтмап
        self::_generate_main_sitemap();
    }
    
    protected static function _clear_sitemap_folder()
    {
        $directory = APPPATH.'../sitemaps/';
        $files     = scandir($directory);
        foreach ($files as $file) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            unlink($directory.$file);    
        }   
    }
    
    protected static function _try_write_file($n, &$urls, $prefix = 'filter')
    {
        if ($n && ($n % self::$_links_per_file == 0)) {
            self::_write_file($urls, $n, $prefix);
            
            $urls = array();        
        }    
    }
    
    protected static function _write_file($urls, $n, $prefix = 'filter')
    {
        $number_file = floor(($n - 1) / self::$_links_per_file) + 1;      
        $directory   = APPPATH.'../sitemaps/';
        $filename    = $directory.$prefix.$number_file.'.xml';
        
        $handler = fopen($filename, 'w');
        fputs($handler, "<?xml version='1.0' encoding='UTF-8'?>\r\n<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>\r\n");
        foreach ($urls as $url) {
            fputs($handler, "\t<url>\r\n\t\t<loc>http://stylemay.ru{$url}</loc>\r\n\t</url>\r\n");        
        }
        fputs($handler, "</urlset>");
        fclose($handler);
    }
    
    protected static function _generate_main_sitemap()
    {
        $directory = APPPATH.'../sitemaps/';
        $_files    = scandir($directory);
        $files     = array();
        foreach ($_files as $file) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            $files[] = $file;   
        }
        
        $sitemap = APPPATH.'../sitemap.xml';
        $handler = fopen($sitemap, 'w'); 
        fputs($handler, "<?xml version='1.0' encoding='UTF-8'?>\r\n<sitemapindex xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>\r\n");
        foreach ($files as $file) {
            fputs($handler, "\t<sitemap>\r\n\t\t<loc>http://stylemay.ru/sitemaps/{$file}</loc>\r\n\t</sitemap>\r\n");        
        }
        fputs($handler, "</sitemapindex>");     
    }
}